<template>
  <div class="customer-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户管理</span>
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增客户</el-button>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="客户编码">
          <el-input
            v-model="searchForm.customer_code"
            placeholder="请输入客户编码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customer_name"
            placeholder="请输入客户名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select
            v-model="searchForm.customer_type"
            placeholder="请选择客户类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(label, value) in customerTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select
            v-model="searchForm.customer_level"
            placeholder="请选择客户等级"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(label, value) in customerLevelOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 客户列表 -->
      <el-table
        v-loading="customerStore.loading"
        :data="customerStore.paginatedCustomers"
        style="width: 100%"
        border
      >
        <el-table-column prop="customer_code" label="客户编码" width="120" />
        <el-table-column prop="customer_name" label="客户名称" width="180" />
        <el-table-column prop="customer_type" label="客户类型" width="120">
          <template #default="scope">
            {{ getCustomerTypeLabel(scope.row.customer_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="customer_level" label="客户等级" width="120">
          <template #default="scope">
            {{ getCustomerLevelLabel(scope.row.customer_level) }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_person" label="联系人" width="120" />
        <el-table-column prop="contact_phone" label="联系电话" width="150" />
        <el-table-column prop="email" label="电子邮箱" width="180" />
        <el-table-column prop="address" label="客户地址" />
        <el-table-column prop="tax_number" label="税号" width="180" />
        <el-table-column prop="credit_limit" label="信用额度" width="120" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_active"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
              :disabled="!hasPermission('customer:status')"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              link
              @click="handleEdit(scope.row)"
              :disabled="!hasPermission('customer:edit')"
            >
              编辑
            </el-button>
            <el-button
              link
              danger
              @click="handleDelete(scope.row)"
              :disabled="!hasPermission('customer:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="customerStore.currentPage"
          v-model:page-size="customerStore.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="customerStore.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑客户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="customerFormRef"
        :model="customerForm"
        :rules="formRules"
        label-width="140px"
        class="dialog-form"
      >
        <el-form-item label="客户编码" prop="customer_code">
          <el-input
            v-model="customerForm.customer_code"
            placeholder="请输入客户编码"
            clearable
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customer_name">
          <el-input
            v-model="customerForm.customer_name"
            placeholder="请输入客户名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户类型" prop="customer_type">
          <el-select
            v-model="customerForm.customer_type"
            placeholder="请选择客户类型"
            clearable
          >
            <el-option
              v-for="(label, value) in customerTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="customer_level">
          <el-select
            v-model="customerForm.customer_level"
            placeholder="请选择客户等级"
            clearable
          >
            <el-option
              v-for="(label, value) in customerLevelOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact_person">
          <el-input
            v-model="customerForm.contact_person"
            placeholder="请输入联系人姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input
            v-model="customerForm.contact_phone"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="customerForm.email"
            placeholder="请输入电子邮箱"
            type="email"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户地址" prop="address">
          <el-input
            v-model="customerForm.address"
            placeholder="请输入客户地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="税号" prop="tax_number">
          <el-input
            v-model="customerForm.tax_number"
            placeholder="请输入税号"
            clearable
          />
        </el-form-item>
        <el-form-item label="开户银行" prop="bank_name">
          <el-input
            v-model="customerForm.bank_name"
            placeholder="请输入开户银行"
            clearable
          />
        </el-form-item>
        <el-form-item label="银行账号" prop="bank_account">
          <el-input
            v-model="customerForm.bank_account"
            placeholder="请输入银行账号"
            clearable
          />
        </el-form-item>
        <el-form-item label="信用额度" prop="credit_limit">
          <el-input-number
            v-model="customerForm.credit_limit"
            placeholder="请输入信用额度"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="付款条件" prop="payment_terms">
          <el-input
            v-model="customerForm.payment_terms"
            placeholder="请输入付款条件"
            clearable
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="customerForm.description"
            placeholder="请输入客户描述"
            type="textarea"
            rows="3"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseCustomerStore } from '@/stores/base/BaseCustomerStore';
import type { Customer, CustomerQueryParams, CustomerCreateParams, CustomerUpdateParams } from '@/types/base/BaseCustomer';

// 客户类型选项
const customerTypeOptions: Record<number, string> = {
  1: '普通客户',
  2: 'VIP客户',
  3: '战略客户'
};

// 客户等级选项
const customerLevelOptions: Record<number, string> = {
  1: 'A级',
  2: 'B级',
  3: 'C级'
};

// 获取客户类型标签
const getCustomerTypeLabel = (type: number): string => {
  return customerTypeOptions[type] || '未知';
};

// 获取客户等级标签
const getCustomerLevelLabel = (level: number): string => {
  return customerLevelOptions[level] || '未知';
};

// 表单验证规则
const formRules = reactive({
  customer_code: [
    { required: true, message: '请输入客户编码', trigger: 'blur' },
    { min: 2, max: 50, message: '客户编码长度应在 2-50 个字符之间', trigger: 'blur' }
  ],
  customer_name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 100, message: '客户名称长度应在 2-100 个字符之间', trigger: 'blur' }
  ],
  customer_type: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  customer_level: [
    { required: true, message: '请选择客户等级', trigger: 'change' }
  ],
  contact_person: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '联系人姓名长度应在 2-50 个字符之间', trigger: 'blur' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: ['blur', 'change'] }
  ],
  address: [
    { required: true, message: '请输入客户地址', trigger: 'blur' }
  ]
});

// 搜索表单
const searchForm = reactive<CustomerQueryParams>({
  customer_code: undefined,
  customer_name: undefined,
  customer_type: undefined,
  customer_level: undefined,
  is_active: undefined
});

// 对话框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = computed(() => isEdit.value ? '编辑客户' : '新增客户');

// 表单数据
const customerForm = reactive({
  customer_id: 0,
  customer_code: '',
  customer_name: '',
  customer_type: undefined,
  customer_level: undefined,
  contact_person: '',
  contact_phone: '',
  email: '',
  address: '',
  tax_number: '',
  bank_name: '',
  bank_account: '',
  credit_limit: undefined,
  payment_terms: '',
  description: ''
});

// 表单引用
const customerFormRef = ref();

// Store实例
const customerStore = useBaseCustomerStore();

// 初始化加载数据
onMounted(() => {
  loadCustomers();
});

// 加载客户列表
const loadCustomers = async () => {
  try {
    await customerStore.getCustomers({
      ...searchForm,
      page_number: customerStore.currentPage,
      page_size: customerStore.pageSize
    });
  } catch (error) {
    ElMessage.error('加载客户列表失败');
  }
};

// 处理搜索
const handleSearch = () => {
  customerStore.setQueryParams(searchForm);
  loadCustomers();
};

// 处理重置
const handleReset = () => {
  searchForm.customer_code = undefined;
  searchForm.customer_name = undefined;
  searchForm.customer_type = undefined;
  searchForm.customer_level = undefined;
  searchForm.is_active = undefined;
  customerStore.resetQueryParams();
  loadCustomers();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  customerStore.setPagination(1, size);
  loadCustomers();
};

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  customerStore.setPagination(current, customerStore.pageSize);
  loadCustomers();
};

// 处理新增 - 修复类型错误：按字段类型重置表单
const handleAdd = () => {
  isEdit.value = false;

  // 按字段类型重置表单
  customerForm.customer_id = 0;
  customerForm.customer_code = '';
  customerForm.customer_name = '';
  customerForm.customer_type = undefined;
  customerForm.customer_level = undefined;
  customerForm.contact_person = '';
  customerForm.contact_phone = '';
  customerForm.email = '';
  customerForm.address = '';
  customerForm.tax_number = '';
  customerForm.bank_name = '';
  customerForm.bank_account = '';
  customerForm.credit_limit = undefined;
  customerForm.payment_terms = '';

  // 移除：description属性重置
  dialogVisible.value = true;
};

// 处理编辑 - 修复API响应数据访问错误
const handleEdit = async (row: Customer) => {
  try {
    // 获取客户详情（假设返回Axios响应对象）
    const response = await customerStore.getCustomerDetail(row.customer_id);
    // 从response.data获取实际客户数据（修复"AxiosResponse上不存在属性"错误）
    const detail = response.data;

    if (detail) {
      isEdit.value = true;
      // 复制数据到表单
      Object.assign(customerForm, {
        customer_id: detail.customer_id,
        customer_code: detail.customer_code,
        customer_name: detail.customer_name,
        customer_type: detail.customer_type,
        customer_level: detail.customer_level,
        contact_person: detail.contact_person,
        contact_phone: detail.contact_phone,
        email: detail.email,
        address: detail.address,
        tax_number: detail.tax_number,
        bank_name: detail.bank_name,
        bank_account: detail.bank_account,
        credit_limit: detail.credit_limit,
        payment_terms: detail.payment_terms,

        // 移除：description属性赋值
      });
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取客户详情失败');
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!customerFormRef.value) return;

  try {
    // 表单验证
    await customerFormRef.value.validate();

    if (isEdit.value) {
      // 编辑模式
      const params: CustomerUpdateParams = {
        customer_id: customerForm.customer_id,
        customer_code: customerForm.customer_code,
        customer_name: customerForm.customer_name,
        customer_type: customerForm.customer_type!,
        customer_level: customerForm.customer_level!,
        contact_person: customerForm.contact_person,
        contact_phone: customerForm.contact_phone,
        email: customerForm.email,
        address: customerForm.address,
        tax_number: customerForm.tax_number,
        bank_name: customerForm.bank_name,
        bank_account: customerForm.bank_account,
        credit_limit: customerForm.credit_limit,
        payment_terms: customerForm.payment_terms
      };
      await customerStore.updateCustomer(params);
      ElMessage.success('客户更新成功');
    } else {
      // 新增模式
      const params: CustomerCreateParams = {
        customer_code: customerForm.customer_code,
        customer_name: customerForm.customer_name,
        customer_type: customerForm.customer_type!,
        customer_level: customerForm.customer_level!,
        contact_person: customerForm.contact_person,
        contact_phone: customerForm.contact_phone,
        email: customerForm.email,
        address: customerForm.address,
        tax_number: customerForm.tax_number,
        bank_name: customerForm.bank_name,
        bank_account: customerForm.bank_account,
        credit_limit: customerForm.credit_limit,
        payment_terms: customerForm.payment_terms
      };
      await customerStore.createCustomer(params);
      ElMessage.success('客户创建成功');
    }

    dialogVisible.value = false;
    loadCustomers();
  } catch (error) {
    // 表单验证失败或API调用失败不处理，已有相应提示
  }
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
  customerFormRef.value?.resetFields();
};

// 处理状态变更
const handleStatusChange = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该客户吗？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await customerStore.toggleCustomerStatus({
      customer_id: row.customer_id,
      is_active: row.is_active
    });
    loadCustomers();
  } catch (error) {
    // 恢复状态
    row.is_active = !row.is_active;
    // 用户取消不提示错误
    if (error !== 'cancel') {
      ElMessage.error('状态变更失败');
    }
  }
};

// 处理删除
const handleDelete = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该客户吗？此操作不可撤销！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    );

    await customerStore.deleteCustomer(row.customer_id);
    loadCustomers();
  } catch (error) {
    // 用户取消不提示错误
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 权限检查
const hasPermission = (permission: string): boolean => {
  // 实际项目中应从权限系统获取
  return true;
};
</script>

<style scoped>
.customer-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}
</style>
